package task

import (
	"errors"
	"k8s-admin/dao/task"
	"k8s-admin/global"
	"k8s-admin/models"
	"k8s-admin/utils"
)

type TaskInterface interface {
	Create(req *models.TaskReq) error
	List() (*models.TaskRes, error)
	StartTask(shell_exec, hosts_ip, module, task_number string) (*string, error)
	HistoryLists() (*models.TaskRes, error)
	Delete(TaskNumber string) error
	Update(TasksNumber string, req *models.TaskReq) error
}

type TaskInfo struct {
}

func NewTaskInterface() TaskInterface {
	return &TaskInfo{}
}

func (t *TaskInfo) Create(req *models.TaskReq) error {
	err := task.NewInterfaceTasks().Create(req)
	if err != nil {
		global.TPLogger.Error(err)
		return errors.New("任务创建失败")
	} else {
		return nil
	}
}
func (t *TaskInfo) List() (*models.TaskRes, error) {
	list, err := task.NewInterfaceTasks().List()
	if err != nil {
		global.TPLogger.Error(err)
		return nil, errors.New("加载失败")
	} else {
		return list, nil
	}
}

func (t *TaskInfo) StartTask(shell_exec, hosts_ip, module, task_number string) (*string, error) {
	ansible_mcd := utils.Ansible{
		Args:       shell_exec,
		Inventory:  hosts_ip,
		ModuleName: module,
	}
	data, err := ansible_mcd.RunAnsible(task_number)
	if err != nil {
		global.TPLogger.Error(err)
		return nil, errors.New("任务执行失败")
	} else {

		return &data, nil
	}
}

func (t *TaskInfo) HistoryLists() (*models.TaskRes, error) {
	list, err := task.NewInterfaceTasks().HistoryLists()
	if err != nil {
		global.TPLogger.Error(err)
		return nil, errors.New("加载失败")
	} else {
		return list, nil
	}
}

func (t *TaskInfo) Delete(TaskNumber string) error {
	err := task.NewInterfaceTasks().Delete(TaskNumber)
	if err != nil {
		global.TPLogger.Error(err)
		return errors.New("删除失败")
	} else {
		return nil
	}
}

func (t *TaskInfo) Update(TasksNumber string, req *models.TaskReq) error {
	err := task.NewInterfaceTasks().Update(TasksNumber, req)
	if err != nil {
		global.TPLogger.Error(err)
		return errors.New("更新失败")
	} else {
		return nil
	}
}
